package com.dengqi.mymodule.activity.permission;

import android.Manifest;
import android.app.Activity;
import android.app.FragmentManager;

/**
 * Created by dell on 2018/7/16
 */
public class PermissionUtils {

    private final String TAG = "RxPermissions";
    private PremissionFragment premissionFragment;

    public PermissionUtils(Activity activity) {
        premissionFragment = getPermissionsFragment(activity);
    }


    private PremissionFragment getPermissionsFragment(Activity activity) {
        FragmentManager fragmentManager = activity.getFragmentManager();
        PremissionFragment permissionsFragment = (PremissionFragment) fragmentManager.findFragmentByTag(TAG);
        boolean isNewInstance = permissionsFragment == null;
        if (isNewInstance) {
            permissionsFragment = PremissionFragment.newInstance();
            fragmentManager
                    .beginTransaction()
                    .add(permissionsFragment, TAG)
                    .commitAllowingStateLoss();
            fragmentManager.executePendingTransactions();
        }
        return permissionsFragment;
    }


    /**
     * 申请拍照
     */
    public void requestCamera(OnCallBack listener) {
        request(new String[]{Manifest.permission.CAMERA}, true, listener);
    }

    /**
     * 申请打电话
     */
    public void requestCallPhone(OnCallBack listener) {
        request(new String[]{Manifest.permission.CALL_PHONE}, true, listener);
    }

    /**
     * 申请存储
     */
    public void requestStorage(OnCallBack listener) {
        request(new String[]{Manifest.permission.WRITE_EXTERNAL_STORAGE, Manifest.permission.READ_EXTERNAL_STORAGE}, true, listener);
    }

    /**
     * 申请拍照
     */
    public void requestCalendar(OnCallBack listener) {
        request(new String[]{Manifest.permission.WRITE_CALENDAR, Manifest.permission.READ_CALENDAR}, true, listener);
    }

    public void request(String[] permissions, boolean isMust, PermissionUtils.OnCallBack listener) {
        premissionFragment.request(permissions, isMust, listener);
    }

    public interface OnCallBack {
        //同意申请的权限 或者 拒绝非必须申请的权限
        void grantSuccess();

        //拒绝必须申请的权限
        void grantFailed();
    }
}
